<?php
declare (strict_types=1);

namespace app\service\logic\common\chat;

use app\facade\StringFacade;
use app\model\communal\ImMessageModel;
use app\service\logic\BaseService;
use Carbon\Carbon;
use think\db\Query;
use think\facade\Db;

final class FriendsService extends BaseService
{
    protected string $modelClassName = 'ImFriendsModel';

    /**
     * 客服获取用户好友列表
     *
     * @param $params
     * @param array $search
     * @return array
     */
    public function getFriendsByAdmin($params, $search = [])
    {
        $where = [
            ['iuaf.admin_id', '=', $search['admin_id']],
            ['u.delete_at', '=', 0]
        ];

        $unFun = function (Query $query) use ($params) {
            $query->whereLike('u.name', '%' . $params['user_name'] . '%');
        };

        $order = 'chat_created_at' . ' ' . 'desc';
        // 复杂查询 DB-#-
        $query = Db::connect('communal')->view(['56001_im_friends' => 'iuaf'], ['user_id', 'admin_id'])
            ->view(['56000_im_message' => 'im'], ['type', 'state' => 'chat_state', 'content' => 'chat_content', 'created_at' => 'chat_created_at'], "im.chat_mark = concat('Admin_', iuaf.admin_id, '_User_', iuaf.user_id) and im.`id` in (select max(`id`) from `56000_im_message` im2 where im2.state in (1,2) and type = 1 group by im2.chat_mark)", 'LEFT')
            ->view(['55000_user' => 'u'], ['name' => 'user_name', 'avatar' => 'user_avatar'], 'iuaf.user_id = u.id', 'LEFT')
            ->when(!empty($params['user_name']), $unFun)
            ->where($where)
            ->orderRaw($order);
        if (isset($params['page']) && isset($params['page_size'])) {
            // 分页
            list($page, $page_size) = $this->pageByParams($params);
            $query->page($page, $page_size);
        }
        $list = $query->select()
            ->each(function ($item) use ($search) {
                // 头像
                $item['user_avatar'] = !empty($item['user_avatar']) ? StringFacade::splicingDomainShowUrl($item['user_avatar']) : config('domain.api') . '/static/web/images/default_avatar.png';
                // 是否存在未读
                $unreadCount = invoke(ChatService::class)->getNumberByState($item['user_id'], ImMessageModel::MORPH_TYPE_TWO, $search['admin_id'], ImMessageModel::MORPH_TYPE_ONE, ImMessageModel::STATE_ONE);
                $item['chat_state'] = $unreadCount > 0 ? ImMessageModel::STATE_ONE : ImMessageModel::STATE_TWO;
                // chat_content处理
                if (empty($item['chat_content'])) {
                    $item['type'] = '1';
                    $item['chat_content'] = '暂无消息';
                    $item['chat_created_at'] = '';
                } else {
                    $item['chat_created_at'] = Carbon::createFromTimestamp($item['chat_created_at'])->format('Y-m-d H:i');
                }
                return $item;
            });
        $total = Db::connect('communal')->view(['56001_im_friends' => 'iuaf'], ['user_id', 'admin_id'])
            ->view(['56000_im_message' => 'im'], ['state' => 'chat_state', 'content' => 'chat_content', 'created_at' => 'chat_created_at'], "im.chat_mark = concat('Admin_', iuaf.admin_id, '_User_', iuaf.user_id) and im.`id` in (select max(`id`) from `56000_im_message` im2 where im2.state in (1,2) group by im2.chat_mark)", 'LEFT')
            ->view(['55000_user' => 'u'], ['name' => 'user_name', 'avatar' => 'user_avatar'], 'iuaf.user_id = u.id', 'LEFT')
            ->when(!empty($params['user_name']), $unFun)
            ->where($where)
            ->count();

        return [
            'items' => $list,
            'total' => $total,
        ];
    }
}
